<template>
  <div class="questionnaire">
    <el-card class="questionnaire-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon size="20" color="#2e7d32"><EditPen /></el-icon>
          <span>{{ title }}</span>
          <el-tag v-if="isCompleted" type="success" size="small">已完成</el-tag>
        </div>
      </template>
      
      <div class="questionnaire-content">
        <!-- 问卷说明 -->
        <div v-if="!isStarted && !isCompleted" class="questionnaire-intro">
          <div class="intro-content">
            <h3>{{ title }}</h3>
            <p class="description">{{ description }}</p>
            <div class="meta-info">
              <el-tag size="small">{{ questions.length }} 个问题</el-tag>
              <el-tag size="small" type="info">预计用时 {{ estimatedTime }} 分钟</el-tag>
            </div>
            <el-button type="primary" size="large" @click="startQuestionnaire">
              开始填写
            </el-button>
          </div>
        </div>
        
        <!-- 问卷填写 -->
        <div v-else-if="isStarted && !isCompleted" class="questionnaire-form">
          <!-- 进度条 -->
          <div class="progress-section">
            <div class="progress-info">
              <span>进度: {{ currentQuestionIndex + 1 }} / {{ questions.length }}</span>
              <span>{{ Math.round(((currentQuestionIndex + 1) / questions.length) * 100) }}%</span>
            </div>
            <el-progress 
              :percentage="((currentQuestionIndex + 1) / questions.length) * 100"
              :status="progressStatus"
            />
          </div>
          
          <!-- 当前问题 -->
          <div class="current-question">
            <div class="question-header">
              <h3 class="question-title">
                <span class="question-number">Q{{ currentQuestionIndex + 1 }}</span>
                {{ currentQuestion.title }}
                <el-tag v-if="currentQuestion.required" type="danger" size="small">必填</el-tag>
              </h3>
              <p v-if="currentQuestion.description" class="question-description">
                {{ currentQuestion.description }}
              </p>
            </div>
            
            <div class="question-content">
              <!-- 单选题 -->
              <el-radio-group 
                v-if="currentQuestion.type === 'single'"
                v-model="answers[currentQuestion.id]"
                class="question-options"
              >
                <el-radio 
                  v-for="option in currentQuestion.options" 
                  :key="option.value"
                  :label="option.value"
                  class="option-item"
                >
                  {{ option.label }}
                </el-radio>
              </el-radio-group>
              
              <!-- 多选题 -->
              <el-checkbox-group 
                v-else-if="currentQuestion.type === 'multiple'"
                v-model="answers[currentQuestion.id]"
                class="question-options"
              >
                <el-checkbox 
                  v-for="option in currentQuestion.options" 
                  :key="option.value"
                  :label="option.value"
                  class="option-item"
                >
                  {{ option.label }}
                </el-checkbox>
              </el-checkbox-group>
              
              <!-- 填空题 -->
              <el-input
                v-else-if="currentQuestion.type === 'text'"
                v-model="answers[currentQuestion.id]"
                type="textarea"
                :rows="4"
                :placeholder="currentQuestion.placeholder || '请输入您的答案'"
                :maxlength="currentQuestion.maxLength || undefined"
                :show-word-limit="currentQuestion.maxLength && currentQuestion.maxLength > 0"
              />
              
              <!-- 评分题 -->
              <div v-else-if="currentQuestion.type === 'rating'" class="rating-question">
                <el-rate
                  v-model="answers[currentQuestion.id]"
                  :max="currentQuestion.maxRating || 5"
                  :show-score="true"
                  :show-text="true"
                />
                <p class="rating-tip">请根据您的满意度进行评分</p>
              </div>
            </div>
            
            <!-- 问题导航 -->
            <div class="question-navigation">
              <el-button 
                v-if="currentQuestionIndex > 0"
                @click="previousQuestion"
              >
                上一题
              </el-button>
              
              <el-button 
                v-if="currentQuestionIndex < questions.length - 1"
                type="primary"
                @click="nextQuestion"
                :disabled="!canProceed"
              >
                下一题
              </el-button>
              
              <el-button 
                v-if="currentQuestionIndex === questions.length - 1"
                type="success"
                @click="submitQuestionnaire"
                :disabled="!canProceed"
              >
                提交问卷
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 问卷结果 -->
        <div v-else-if="isCompleted" class="questionnaire-result">
          <div class="result-header">
            <el-icon size="48" color="#67c23a"><CircleCheck /></el-icon>
            <h3>问卷提交成功！</h3>
            <p>感谢您的参与，您的反馈对我们很重要。</p>
          </div>
          
          <div class="result-actions">
            <el-button @click="restartQuestionnaire">重新填写</el-button>
            <el-button type="primary" @click="exportResult">导出结果</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { EditPen, CircleCheck, ArrowRight, ArrowLeft, Download } from '@element-plus/icons-vue'

// 问题类型定义
interface QuestionOption {
  label: string
  value: any
}

interface Question {
  id: string
  title: string
  description?: string
  type: 'single' | 'multiple' | 'text' | 'rating'
  required?: boolean
  options?: QuestionOption[]
  maxLength?: number
  placeholder?: string
  maxRating?: number
}

// 组件属性
interface Props {
  title: string
  description?: string
  questions: Question[]
  estimatedTime?: number
}

// 组件事件
interface Emits {
  (e: 'submit', answers: Record<string, any>): void
}

const props = withDefaults(defineProps<Props>(), {
  description: '请认真填写以下问题，您的反馈对我们很重要。',
  estimatedTime: 5
})

const emit = defineEmits<Emits>()

// 状态管理
const isStarted = ref(false)
const isCompleted = ref(false)
const currentQuestionIndex = ref(0)
const answers = reactive<Record<string, any>>({})

// 计算属性
const currentQuestion = computed(() => {
  if (!props.questions || !Array.isArray(props.questions) || props.questions.length === 0) {
    return null;
  }
  return props.questions[currentQuestionIndex.value]
})

const progressStatus = computed(() => {
  if (!props.questions || !Array.isArray(props.questions) || props.questions.length === 0) {
    return '';
  }

  const progress = ((currentQuestionIndex.value + 1) / props.questions.length) * 100
  if (progress >= 100) return 'success'
  if (progress >= 80) return 'warning'
  return ''
})

const canProceed = computed(() => {
  const question = currentQuestion.value
  if (!question) return false
  
  const answer = answers[question.id]
  
  if (question.required) {
    if (question.type === 'multiple') {
      return Array.isArray(answer) && answer.length > 0
    } else {
      return answer !== undefined && answer !== null && answer !== ''
    }
  }
  
  return true
})

// 方法
const startQuestionnaire = () => {
  isStarted.value = true
  
  // 初始化答案
  if (!props.questions || !Array.isArray(props.questions)) {
    return;
  }

  props.questions.forEach(question => {
    if (question.type === 'multiple') {
      answers[question.id] = []
    }
  })
}

const nextQuestion = () => {
  if (!props.questions || !Array.isArray(props.questions)) {
    return;
  }

  if (currentQuestionIndex.value < props.questions.length - 1) {
    currentQuestionIndex.value++
  }
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const submitQuestionnaire = () => {
  try {
    // 验证所有必填题
    const requiredQuestions = props.questions.filter(q => q.required)
    const missingAnswers = requiredQuestions.filter(q => {
      const answer = answers[q.id]
      if (q.type === 'multiple') {
        return !Array.isArray(answer) || answer.length === 0
      } else {
        return answer === undefined || answer === null || answer === ''
      }
    })
    
    if (missingAnswers.length > 0) {
      ElMessage.error(`还有 ${missingAnswers.length} 个必填题未完成`)
      return
    }
    
    // 标记完成
    isCompleted.value = true
    
    // 发送提交事件
    emit('submit', { ...answers })
    
    ElMessage.success('问卷提交成功！')
  } catch (error) {
    console.error('提交问卷失败:', error)
    ElMessage.error('提交失败，请重试')
  }
}

const restartQuestionnaire = () => {
  isStarted.value = false
  isCompleted.value = false
  currentQuestionIndex.value = 0
  
  // 清空答案
  Object.keys(answers).forEach(key => {
    delete answers[key]
  })
}

const exportResult = () => {
  try {
    const result = {
      title: props.title,
      submitTime: new Date().toISOString(),
      questions: props.questions.map((q, index) => ({
        number: index + 1,
        title: q.title,
        type: q.type,
        answer: formatAnswer(q, answers[q.id])
      }))
    }
    
    const dataStr = JSON.stringify(result, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${props.title}-结果-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success('结果导出成功')
  } catch (error) {
    console.error('导出结果失败:', error)
    ElMessage.error('导出失败')
  }
}

// 工具方法
const formatAnswer = (question: Question, answer: any) => {
  if (answer === undefined || answer === null || answer === '') {
    return '未填写'
  }
  
  switch (question.type) {
    case 'single':
      const singleOption = question.options?.find(opt => opt.value === answer)
      return singleOption?.label || answer
      
    case 'multiple':
      if (Array.isArray(answer)) {
        const labels = answer.map(val => {
          const option = question.options?.find(opt => opt.value === val)
          return option?.label || val
        })
        return labels.join('、')
      }
      return answer
      
    case 'text':
      return answer
      
    case 'rating':
      return `${answer}分`
      
    default:
      return answer
  }
}

// 暴露方法
defineExpose({
  start: startQuestionnaire,
  submit: submitQuestionnaire,
  restart: restartQuestionnaire,
  getAnswers: () => ({ ...answers })
})
</script>

<style scoped>
.questionnaire {
  width: 100%;
}

.questionnaire-card {
  border-radius: 12px;
  border: 1px solid var(--border-color);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.questionnaire-content {
  padding: 20px 0;
}

.questionnaire-intro {
  text-align: center;
  padding: 40px 20px;
}

.intro-content h3 {
  font-size: 24px;
  color: var(--primary-color);
  margin-bottom: 16px;
}

.description {
  font-size: 16px;
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: 24px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.meta-info {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-bottom: 32px;
}

.progress-section {
  margin-bottom: 32px;
  padding: 20px;
  background: var(--background-secondary);
  border-radius: 8px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: var(--text-secondary);
}

.current-question {
  padding: 20px;
  background: white;
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.question-header {
  margin-bottom: 24px;
}

.question-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 12px;
  font-size: 18px;
  color: var(--text-primary);
}

.question-number {
  background: var(--primary-color);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
}

.question-description {
  margin: 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.question-content {
  margin-bottom: 32px;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  padding: 12px 16px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.option-item:hover {
  border-color: var(--primary-color);
  background: rgba(46, 125, 50, 0.05);
}

.rating-question {
  text-align: center;
}

.rating-tip {
  margin: 16px 0 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.question-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 24px;
  border-top: 1px solid var(--border-color);
}

.questionnaire-result {
  text-align: center;
  padding: 40px 20px;
}

.result-header {
  margin-bottom: 40px;
}

.result-header h3 {
  font-size: 24px;
  color: var(--success-color);
  margin: 16px 0 12px;
}

.result-header p {
  color: var(--text-secondary);
  font-size: 16px;
  margin: 0;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}
</style>
